#include "qwcomboboxdelegate.h"
#include <QComboBox>

QwComboBoxDelegate::QwComboBoxDelegate(QObject *parent)
    : QStyledItemDelegate{parent}
{}

QWidget *QwComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    Q_UNUSED(option);
    Q_UNUSED(index);
    // 创建代理编辑组件
    QComboBox *editor = new QComboBox(parent);
    editor->setFrame(false); // 无边框
    editor->addItems(QStringList() << "=" << ">" << "<");
    return editor;
}

void QwComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
    // 从数据模型中获取数据，显示到代理组件中
    QString value = index.model()->data(index, Qt::EditRole).toString();
    QComboBox *comboBox = static_cast<QComboBox*>(editor);
    comboBox->setCurrentText(value);
}

void QwComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const {
    // 将代理编辑组件的数据保存到数据模型中
    QComboBox *comboBox = static_cast<QComboBox*>(editor);
    QString value = comboBox->currentText();
    model->setData(index, value, Qt::EditRole);
}

void QwComboBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    Q_UNUSED(index);
    // 设置组件大小
    editor->setGeometry(option.rect);
}
